package com.aaa.jdbc;

import com.aaa.jdbc.userinfo.UserInfo;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：Teacher陈（86521760@qq.com）
 * @date ：Created in 2022/7/27 10:41
 * @description：
 * @modified By：
 * @version:
 */
public class QueryTest {

    /**
     * 四大金刚
     */
    static String driver = "com.mysql.jdbc.Driver";
    static String url = "jdbc:mysql://localhost:3306/qy156?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai";
    static String username = "root";
    static String password = "root";

    /**
     * @create by: Teacher陈（86521760@qq.com）
     * @description: 1、加载驱动
     */
    static {
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * @create by: Teacher陈（86521760@qq.com）
     * @description: 2、获取数据库连接
     */
    public static Connection getConnection() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static void main(String[] args) throws Exception {
        Connection connection = QueryTest.getConnection();
        String sql = "select * from emp ";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //执行并返回结果集
        ResultSet resultSet = preparedStatement.executeQuery();
        //获取总列数
        //metaData 元数据，主要保存的是表接口，不包含行数据，
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();
        System.out.println("columnCount总列数：" + columnCount);
        //定义一个list集合，封装多行数据
        List<Map<String, Object>> rowList = new ArrayList<>();
        while (resultSet.next()) {
            //jdbc默认下标从1开始
            Map map = new HashMap<>();
            for (int i = 1; i <= columnCount; i++) {
                //获取列名
                String columnName = metaData.getColumnName(i);
                //获取列值
                Object columnValue = resultSet.getObject(columnName);
                map.put(columnName, columnValue);

            }
            rowList.add(map);
        }
        resultSet.close();
        preparedStatement.close();
        connection.close();

        System.out.println("遍历所有的行");
        for (Map<String, Object> map : rowList) {
            System.out.println(map);
        }
    }
}
